import React, { useEffect } from 'react';
import { connect } from 'umi';
import { router, Link } from 'umi';
import { Card, Table, Button, Divider, message } from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Pagination from '@/components/Pagination';
import PageRouter from '@/components/PageRouter/PageRouter';
import moment from 'moment';
import request from '@/utils/request';
import LinkTo from '@/components/LinkTo';
import { TableFilter } from '@/components';
import authHelpr from '@/utils/auth/helper';
import { useUpdateEffect } from 'react-use';
import FormAdvanced from '../components/FormAdvanced';
import styles from './index.less';

const { checkCode } = authHelpr;

export const defaultQuery = (query = {}) => {
    const {
        companyCode = '',
        departmentCode = '',
        employeeName = '',
        endTime = '',
        startTime = '',
        pageNo = 1,
        pageSize = 10,
        orderType = '',
        orderColumn = null,
        listTab = 3,
        quitStatus = ''
    } = query;
    return {
        companyCode,
        departmentCode,
        employeeName,
        endTime,
        startTime,
        pageNo,
        pageSize,
        orderType,
        orderColumn,
        listTab,
        quitStatus
    };
};
const QuitApproval = props => {
    const { route, location, dispatch, loading, model } = props;
    const { quitList, total, handoverStatus } = model;
    const { query: urlQuery } = location;

    const [query, setQuery] = React.useState(defaultQuery(urlQuery));
    // 列表
    const fetchList = payload => {
        dispatch({
            type: 'QuitManagement/fetch',
            payload
        });
    };
    // 表格筛选，排序
    const handleTableChange = async (pagination, filters, sorter) => {
        const { field, order } = sorter;
        let orderObj = {
            orderColumn: ''
        };
        let statusObj = {
            orderType: ''
        };
        if (field && order) {
            orderObj = {
                orderColumn: field
            };
            statusObj = {
                orderType: order === 'ascend' ? 1 : 2
            };
        }
        let quitStatusObj = {
            quitStatus: ''
        };
        if (filters && filters.quitStatusName && filters.quitStatusName.length > 0) {
            quitStatusObj = {
                quitStatus: filters.quitStatusName[0]
            };
        }
        const { orderColumn, orderType, quitStatus, ...rest } = query;
        const finalQuery = { ...rest, pageNo: 1, ...statusObj, ...quitStatusObj, ...orderObj };
        history.push({ query: finalQuery });
        setQuery(finalQuery);
    };
    // 分页
    const handlePaginationChange = _pagination => {
        const { current, ...rest } = _pagination;
        const finalQuery = { ...query, ...rest, pageNo: current };
        setQuery(finalQuery);
        history.push({ query: finalQuery });
    };
    // 搜索
    const handleSearch = value => {
        const finalQuery = { ...query, ...value, pageNo: 1 };
        setQuery(finalQuery);
        history.push({ query: finalQuery });
    };
    // 清空
    const handleReset = () => {
        const { orderType, orderColumn } = query;
        history.push({ query: { orderType, orderColumn } });
        setQuery({ ...defaultQuery(), orderType, orderColumn });
    };
    const transformFilters = (data = []) =>
        data.map(item => ({
            text: item.name,
            value: item.code
        }));
    const fetchProcessStatus = () => {
        dispatch({
            type: 'QuitManagement/fetchHandoverStatus'
        });
    };
    const columns = [
        {
            title: '离职员工',
            dataIndex: 'employeeName',
            key: 'employeeName',
            width: 100,
            render: (text, record) => {
                const { dutyCode, quitUser } = record;
                const params = { dutyCode, employeeCode: quitUser };
                return (
                    <Link
                        to={{
                            pathname: '/office/personnelManagement/organization/employeeList/detail',
                            query: params
                        }}
                    >
                        {text}
                    </Link>
                );
            }
        },
        {
            title: '行政机构',
            dataIndex: 'companyName',
            key: 'companyName',
            sorter: () => {}
        },
        {
            title: '组织机构',
            dataIndex: 'departmentName',
            key: 'departmentName',
            sorter: () => {}
        },
        {
            title: '职位',
            dataIndex: 'positionName',
            key: 'positionName',
            render: text => (
                <div className={styles.ellipsis} title={text}>
                    {text}
                </div>
            ),
            sorter: () => {}
        },
        {
            title: '职级',
            dataIndex: 'postGradeCode',
            key: 'postGradeCode',
            sorter: () => {}
        },
        {
            title: '入职日期',
            dataIndex: 'timeOfEntry',
            key: 'timeOfEntry',
            width: '160px',
            sorter: () => {}
        },
        {
            title: '离职日期',
            dataIndex: 'actualLeaveDate',
            key: 'actualLeaveDate',
            width: 100,
            sorter: () => {},
            render: text => moment(text).format('YYYY-MM-DD')
        },
        {
            title: '发起时间',
            dataIndex: 'startTime',
            key: 'startTime',
            width: 180,
            sorter: () => {}
        },
        {
            title: '状态',
            dataIndex: 'quitStatusName',
            key: 'quitStatusName',
            width: 100,
            fixed: 'right',
            filters: transformFilters(handoverStatus),
            filterDropdown: filterProps => <TableFilter {...filterProps} />,
            filterMultiple: false
        },
        {
            title: '操作',
            fixed: 'right',
            width: 170,
            render: (text, record) => {
                const {
                    handoverProcessInstanceId,
                    handoverProcessInstanceName,
                    quitProcessInstanceId,
                    quitProcessInstanceName,
                    approveNode,
                    quitProcessDefId
                } = record;
                if (!quitProcessDefId) {
                    return <span> - </span>;
                }
                // 新流程
                if (approveNode) {
                    return (
                        <div>
                            <LinkTo
                                to="/office/personnelManagement/onboardAndLeave/myAuditReadDetail"
                                query={{
                                    processInstanceId: quitProcessInstanceId,
                                    processInstanceName: quitProcessInstanceName
                                }}
                            >
                                审批详情
                            </LinkTo>

                            <Divider type="vertical" />
                            <LinkTo
                                to="/office/personnelManagement/onboardAndLeave/myAuditReadDetail"
                                query={{
                                    processInstanceId: handoverProcessInstanceId,
                                    processInstanceName: handoverProcessInstanceName
                                }}
                                disabled={!handoverProcessInstanceId}
                            >
                                交接详情
                            </LinkTo>
                        </div>
                    );
                }
                // 旧流程
                return (
                    <div>
                        <LinkTo
                            to="/office/personnelManagement/onboardAndLeave/applyLeave"
                            query={{
                                leaveOfficeId: quitProcessDefId,
                                type: 'company'
                            }}
                            disabled={quitProcessDefId === '0'}
                        >
                            历史详情
                        </LinkTo>
                        <Divider type="vertical" />
                        <LinkTo
                            to="/office/personnelManagement/onboardAndLeave/myAuditReadDetail"
                            query={{
                                processInstanceId: handoverProcessInstanceId,
                                processInstanceName: handoverProcessInstanceName
                            }}
                            disabled={!handoverProcessInstanceId}
                        >
                            交接详情
                        </LinkTo>
                    </div>
                );
            }
        }
    ];

    // 跳转办理离职页面
    const showApplyResigned = async () => {
        // 获取登陆人公司id
        const classificationRes = await request(
            '/api/workflowweb/processinstance/v1/getByAdvancedSettingType?classification=quitApply'
        );
        if (classificationRes?.code === 10000) {
            history.push(
                `/personal/portal/apply?id=${classificationRes?.data?.actProcessDefinitionId}&name=${classificationRes?.data?.processName}`
            );
        } else {
            message.error(classificationRes.msg);
        }
    };

    // 首次加载表格数据由高级搜索组件主动触发搜索按钮完成, 要不然没法获取到默认值
    useUpdateEffect(() => {
        fetchList(query);
    }, [query]);

    useEffect(() => {
        fetchProcessStatus();
    }, []);

    return (
        <PageHeaderWrapper>
            <PageRouter
                type="flowMyOnboardAndLeave"
                activePath="/office/personnelManagement/onboardAndLeave/historicalRecords"
                extraButton={
                    checkCode('office:personnel:progress:newleaveoffice:add') && (
                        <Button type="primary" onClick={showApplyResigned}>
                            办理离职
                        </Button>
                    )
                }
            >
                <Card bordered={false} className={styles.temp}>
                    <FormAdvanced
                        onSearch={handleSearch}
                        onReset={handleReset}
                        route={route}
                        // processStatusType={processStatusType}
                        query={query}
                    />
                    <Table
                        rowKey="applicationNo"
                        columns={columns}
                        dataSource={quitList}
                        onChange={handleTableChange}
                        loading={loading}
                        pagination={false}
                        scroll={{ x: 'max-content' }}
                        style={{
                            tableLayout: 'fixed',
                            wordBreak: 'break-word'
                        }}
                    />
                    <Pagination
                        total={total}
                        current={Number(query.pageNo)}
                        pageSize={Number(query.pageSize)}
                        onChange={handlePaginationChange}
                        loading={loading}
                    />
                </Card>
            </PageRouter>
        </PageHeaderWrapper>
    );
};

export default connect(({ QuitManagement, loading }) => ({
    model: QuitManagement,
    loading: loading.models.QuitManagement
}))(QuitApproval);
